package com.qf.interceptors;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    
    private ThreadLocal<String> local = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取用户id
        String userId = request.getHeader("userId");
        
        if (!StringUtils.isEmpty(userId)){
            
            //将用户id存到ThreadLocal中
            local.set(userId);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        
        local.remove();
    }

    public ThreadLocal<String> getLocal() {
        return local;
    }

    public void setLocal(ThreadLocal<String> local) {
        this.local = local;
    }
}
